// 将对象结构的参数格式化成url拼接参数形式
export const parseQuery = () => {
	const res = {};

	const query = (location.href.split("?")[1] || "")
		.trim()
		.replace(/^(\?|#|&)/, "");

	if (!query) {
		return res;
	}

	query.split("&").forEach(param => {
		const parts = param.replace(/\+/g, " ").split("=");
		const key = decodeURIComponent(parts.shift());
		const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;

		if (res[key] === undefined) {
			res[key] = val;
		} else if (Array.isArray(res[key])) {
			res[key].push(val);
		} else {
			res[key] = [res[key], val];
		}
	});

	return res;
}


export const getObjType = obj => {
	const toString = Object.prototype.toString
	const map = {
		'[object Boolean]': 'boolean',
		'[object Number]': 'number',
		'[object String]': 'string',
		'[object Function]': 'function',
		'[object Array]': 'array',
		'[object Date]': 'date',
		'[object RegExp]': 'regExp',
		'[object Undefined]': 'undefined',
		'[object Null]': 'null',
		'[object Object]': 'object'
	}
	if (obj instanceof Element) {
		return 'element'
	}
	return map[toString.call(obj)]
}

/**
 * 对象深拷贝
 */
export const deepClone = data => {
	const type = getObjType(data)
	let obj
	if (type === 'array') {
		obj = []
	} else if (type === 'object') {
		obj = {}
	} else {
		// 不再具有下一层次
		return data
	}
	if (type === 'array') {
		for (let i = 0, len = data.length; i < len; i++) {
			obj.push(deepClone(data[i]))
		}
	} else if (type === 'object') {
		for (const key in data) {
			obj[key] = deepClone(data[key])
		}
	}
	return obj
}



/**
 * 处理服务器扫码带进来的参数
 * @param string param 扫码携带参数
 * @param string k 整体分割符 默认为：&
 * @param string p 单个分隔符 默认为：=
 * @return object
 * 
 */
export const getUrlParams = (param, k, p) => {
	if (typeof param != 'string') return {};
	k = k ? k : '&'; //整体参数分隔符
	p = p ? p : '='; //单个参数分隔符
	var value = {};
	if (param.indexOf(k) !== -1) {
		param = param.split(k);
		for (var val in param) {
			if (param[val].indexOf(p) !== -1) {
				var item = param[val].split(p);
				value[item[0]] = item[1];
			}
		}
	} else if (param.indexOf(p) !== -1) {
		var item = param.split(p);
		value[item[0]] = item[1];
	} else {
		return param;
	}
	return value;
}



/**根据格式组装公共参数
 * @param {Object} value
 */
export const formatMpQrCodeData = (value) => {
	let values = value.split(',');
	let result = {};
	if (values.length === 2) {
		let v1 = values[0].split(":");
		if (v1[0] === 'pid') {
			result.spread = v1[1];
		} else {
			result.id = v1[1];
		}
		let v2 = values[1].split(":");
		if (v2[0] === 'pid') {
			result.spread = v2[1];
		} else {
			result.id = v2[1];
		}
	} else {
		result = values[0].split(":")[1];
	}
	return result;
}

/**
 * @param string num
 */
export const formatDecimal = (num) => {
	if (num) {
		num = num && num.toString();
		let index = num.indexOf('.');
		if (index !== -1) {
			num = num.substring(0, 2 + index + 1);
		} else {
			num = num.substring(0);
		}
		return parseFloat(num).toFixed(2);
	}

	// return uni.$u.priceFormat(num, 2);
}

/**
 *  获取相册权限
 */
export function wxSaveAuth() {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success(res) {
				if (!res.authSetting['scope.writePhotosAlbum']) {
					// 如果没有写入权限，则获取写入相册权限
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success() {
							resolve()
						},
						fail(err) {
							reject(err)
							// 用户拒绝授权
							uni.showModal({
								content: '检测到您没打开捷买士的相册权限，是否去设置打开？',
								confirmText: '确认',
								cancelText: '取消',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success: res => { }
										})
									}
								}
							})
						}
					})
				} else {
					resolve()
				}
			},
			fail(e) {
				reject(e)
			}
		})
	})
}

/**
 *
 * @param {String} url 单张网络图片
 */
//下载内容,临时文件路径
function getTempPath(url) {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: url,
			success: function (res) {
				var temp = res.tempFilePath
				uni.saveImageToPhotosAlbum({
					filePath: temp,
					success: function (res) {
						return resolve(res)
					},
					fail: function (err) {
						reject(url + JSON.stringify(err))
					}
				})
			},
			fail: function (err) {
				reject(url + JSON.stringify(err))
			}
		})
	})
}

/**
 * 多文件下载并且保存 
 * @param {Array} urls 网络图片数组
 */
export function downloadImgs(urls) {
	uni.showLoading({
		title: '图片下载中',
		mask: true
	})
	const imageList = []
	// 循环数组
	for (let i = 0; i < urls.length; i++) {
		imageList.push(getTempPath(urls[i]))
	}
	const loadTask = []
	let index = 0
	while (index < imageList.length) {
		loadTask.push(
			new Promise((resolve, reject) => {
				// 将数据分割成多个promise数组
				Promise.all(imageList.slice(index, (index += 8)))
					.then(res => {
						resolve(res)
					})
					.catch(err => {
						reject(err)
					})
			})
		)
	}
	// Promise.all 所有图片下载完成后弹出
	Promise.all(loadTask)
		.then(res => {
			uni.showToast({
				title: '下载完成',
				duration: 3000
			})
		})
		.catch(err => {
			uni.showToast({
				title: `下载完成`,
				icon: 'none',
				duration: 3000
			})
		})
}
